#!/bin/bash

# 默认变量
ENV="dev"
VERSION="v1.0"
REGISTRY=""
YAML_DIR="/programs/springboot-demo-k8s"

# 参数读取（env version yaml path）
while [[ $# -gt 0 ]]; do
  case "$1" in
    --env=*)
      ENV="${1#*=}"
      shift 2
      ;;
    --version=*)
      VERSION="${1#*=}"
      shift 2
      ;;
    --yaml=*)
      YAML_DIR="${1#*=}"
      shift 2
      ;;
    *)
      shift
      ;;
  esac
done

# 拼接部署路径
YAML_PATH="${YAML_DIR}/${ENV}/user.yaml"
REGISTRY="${REGISTRY}/${ENV}/"

if [ ! -f "$YAML_PATH" ]; then
  echo "❌ YAML 文件不存在: $YAML_PATH"
  exit 1
fi

# 变量替换（创建临时文件）
TEMP_YAML=$(mktemp)
sed -e "s|\${REGISTRY}|${REGISTRY}|g" -e "s|\${VERSION}|${VERSION}|g" "$YAML_PATH" > "$TEMP_YAML"

echo "🔄 删除旧部署..."
kubectl delete -f "$TEMP_YAML" --ignore-not-found

echo "🚀 应用新部署..."
kubectl apply -f "$TEMP_YAML"

echo "⏳ 等待 Pod 启动..."
sleep 3
kubectl get pods -n mate-app -o wide

rm "$TEMP_YAML"
echo "✅ 部署成功: 环境=$ENV，版本=$VERSION"
